package com.xy.biz.mc.service.impl;

import com.xy.biz.mc.connection.SocketConnection;
import com.xy.biz.mc.domain.Message;
import com.xy.biz.mc.service.ConnectionService;
import com.xy.biz.mc.service.PushService;
import com.xy.biz.mc.service.ServerEndPointService;
import com.xy.biz.mc.service.UserConnectionService;
import com.xy.tool.json.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.xy.biz.mc.service.PushService.PREFIX_PUSH_SERVICE;

@Service(PREFIX_PUSH_SERVICE + UserPushServiceImpl.TO_TYPE_USER)
public class UserPushServiceImpl implements PushService {

    final static int TO_TYPE_USER = 1;

    @Autowired
    private UserConnectionService userConnectionService;
    @Autowired
    private ServerEndPointService serverEndPointService;
    @Autowired
    private ConnectionService connectionService;

    @Override
    public void send(Long messageId, Long toId, byte[] data) {
        Long localServerId = serverEndPointService.getServerId();
        Long userId = toId;
        Long serverId = userConnectionService.getServerId(userId);
        if(Objects.equals(localServerId, serverId)) {
            SocketConnection socketConnection = connectionService.getConnection(userId);
            if(socketConnection != null) {
                Message parse = JsonUtils.parse(data, Message.class);
                parse.setMessageId(messageId + "");
                socketConnection.sendText(JsonUtils.toJson(parse));
            }
        } else {

        }
    }

}
